package com.lxlx.weixinlx.controller;

import com.lxlx.weixinlx.domain.Token;
import com.lxlx.weixinlx.domain.User;
import com.lxlx.weixinlx.service.WeiXingLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 127.0.0.1 www.txjava.cn(修改host文件)
 * @author liuhuan
 * @date 2020
 * @描述
 */
@Controller
public class WeiXinLoginController {
    @Autowired
    private WeiXingLoginService weiXingLoginService;

    @GetMapping("/weixinLonin")
    public String weiXinLogin(){
        String url = weiXingLoginService.getLogin();
        System.out.println(url);
        return "redirect:"+url;
    }

    /**
     * 回调
     * @param code
     * @param state
     */
    @GetMapping("/loginServlet")
    public ModelAndView collBack(String code , String state){
        String access_token = null;
        String openid = null;
        ModelAndView modelAndView = new ModelAndView();
        if(code == null && state == null){
            throw new RuntimeException("用户禁止授权...");
        }
        if (!state.equals("123")){
            throw new RuntimeException("登录失败...");
        }
        //请求微信得到token
        Token token = weiXingLoginService.getToken(code);
        if (token != null){
            access_token = token.getAccess_token();
            openid = token.getOpenid();
            //可以做自己的业务处理
            //...........可以查询是否在数据库,,在则查询数据,不在保存为新用户


            //请求用户信息
            User user = weiXingLoginService.getUser(access_token, openid);
            System.out.println(user);
            modelAndView.addObject("userInfo",user);
            modelAndView.setViewName("main");

        }
        return modelAndView;

    }










}
